<template>
    <div class="ewe-delivery-view">
        <!-- 顶部操作栏 -->
        <div class="action-bar">
            <div class="action-left">
                <el-button type="primary" @click="handleAddNew" :icon="Plus" :disabled="!hasTableData">
                    + 新增
                </el-button>
                <el-button type="success" @click="handleSave" :icon="Document"
                    title="请确保负责人、分娩日期已填写，并且至少有一行完整数据（耳号、分娩难易、母性、泌乳、乳房炎、各项羔羊数据）">
                    保存
                </el-button>
                <el-button @click="handleUndo" :icon="RefreshLeft" :disabled="!hasChanges">
                    撤销
                </el-button>
                <el-button type="danger" @click="handleDelete" :icon="Delete" :disabled="!isEditMode">
                    删除
                </el-button>
            </div>
            <div class="action-right">
                <el-icon class="action-icon">
                    <Setting />
                </el-icon>
                <el-icon class="action-icon">
                    <Printer />
                </el-icon>
            </div>
        </div>

        <!-- 头部表单区域 -->
        <div class="form-section">
            <div class="form-row">
                <div class="form-item">
                    <label class="required">负责人</label>
                    <el-select v-model="formData.responsibleFor" placeholder="请选择负责人" clearable>
                        <el-option label="海绵宝宝" value="海绵宝宝" />
                        <el-option label="派大星" value="派大星" />
                        <el-option label="蟹老板" value="蟹老板" />
                    </el-select>
                </div>
                <div class="form-item">
                    <label class="required">分娩日期</label>
                    <el-date-picker v-model="formData.mainDeliveryTime" type="date" placeholder="选择日期" format="YYYY/MM/DD"
                        value-format="YYYY/MM/DD" />
                </div>
                <div class="form-item">
                    <label>单据号</label>
                    <el-input v-model="formData.documentNumber" readonly />
                </div>
                <div class="form-item">
                    <label>流水号</label>
                    <el-input v-model="formData.serialNumber" readonly />
                </div>
            </div>
        </div>

        <!-- 主数据表格区域 -->
        <div class="table-section">
            <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="80" align="center">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="*耳号" width="120">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.ewedeliverySnowId" placeholder="请输入耳号"
                            @blur="validateRequiredField(row, 'ewedeliverySnowId', $index)" />
                    </template>
                </el-table-column>
                <el-table-column label="妊娠天数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryDayNum" :min="0" :max="200" controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="*分娩难易" width="100">
                    <template #default="{ row, $index }">
                        <el-select v-model="row.ewedeliveryDifficulty" placeholder="请选择"
                            @change="validateRequiredField(row, 'ewedeliveryDifficulty', $index)">
                            <el-option label="顺产" :value="true" />
                            <el-option label="难产" :value="false" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="母性" width="100">
                    <template #default="{ row }">
                        <el-select v-model="row.ewedeliveryMamhood" placeholder="请选择">
                            <el-option label="良好" value="良好" />
                            <el-option label="一般" value="一般" />
                            <el-option label="较差" value="较差" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="泌乳" width="100">
                    <template #default="{ row }">
                        <el-select v-model="row.ewedeliveryLactation" placeholder="请选择">
                            <el-option label="良好" value="良好" />
                            <el-option label="一般" value="一般" />
                            <el-option label="较差" value="较差" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="乳房炎" width="100">
                    <template #default="{ row }">
                        <el-select v-model="row.ewedeliveryMastitis" placeholder="请选择">
                            <el-option label="无" value="无" />
                            <el-option label="轻微" value="轻微" />
                            <el-option label="严重" value="严重" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="窝号" width="100">
                    <template #default="{ row }">
                        <el-input v-model="row.ewedeliveryWoHao" />
                    </template>
                </el-table-column>
                <el-table-column label="健羔数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryHealthy" :min="0" :max="10" controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="弱羔数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryLamb" :min="0" :max="10" controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="畸形数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryDeformities" :min="0" :max="10"
                            controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="死胎数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryNumNums" :min="0" :max="10" controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="木乃伊数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryMummies" :min="0" :max="10" controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="活羔数" width="100">
                    <template #default="{ row }">
                        <el-input-number v-model="row.ewedeliveryHoof" :min="0" :max="10" controls-position="right" />
                    </template>
                </el-table-column>
                <el-table-column label="性别" width="100">
                    <template #default="{ row }">
                        <el-select v-model="row.ewedeliverySex" placeholder="请选择">
                            <el-option label="公" :value="true" />
                            <el-option label="母" :value="false" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="当前栋舍" width="120">
                    <template #default="{ row }">
                        <el-input v-model="row.ewedeliveryPoultryhome" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="当前栏位" width="120">
                    <template #default="{ row }">
                        <el-input v-model="row.ewedeliveryField" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="转入栋舍" width="120">
                    <template #default="{ row }">
                        <el-input v-model="row.ewedeliveryTransferhouse" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="转入栏位" width="120">
                    <template #default="{ row }">
                        <el-input v-model="row.ewedeliveryTransfer" placeholder="请输入" />
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 底部操作和统计区域 -->
        <div class="footer-section">
            <div class="row-actions">
                <el-button type="primary" @click="handleAddRow" :icon="Plus">
                    + 增行
                </el-button>
                <el-button type="warning" @click="handleCleanInvalidRows" :icon="Delete">
                    清理无效行
                </el-button>
                <el-button type="danger" @click="handleDeleteRows" :icon="Delete">
                    - 删行
                </el-button>
            </div>

            <div class="summary-section">
                <div class="summary-label">合计</div>
                <div class="totals-section">
                    <div class="total-item">
                        <span class="total-label">健羔数:</span>
                        <span class="total-value">{{ totals.ewedeliveryHealthy.toFixed(0) }}</span>
                    </div>
                    <div class="total-item">
                        <span class="total-label">弱羔数:</span>
                        <span class="total-value">{{ totals.ewedeliveryLamb.toFixed(0) }}</span>
                    </div>
                    <div class="total-item">
                        <span class="total-label">畸形数:</span>
                        <span class="total-value">{{ totals.ewedeliveryDeformities.toFixed(0) }}</span>
                    </div>
                    <div class="total-item">
                        <span class="total-label">死胎数:</span>
                        <span class="total-value">{{ totals.ewedeliveryStillbirths.toFixed(0) }}</span>
                    </div>
                    <div class="total-item">
                        <span class="total-label">木乃伊数:</span>
                        <span class="total-value">{{ totals.ewedeliveryMummies.toFixed(0) }}</span>
                    </div>
                    <!-- <div class="total-item">
                        <span class="total-label">活羔数:</span>
                        <span class="total-value">{{ totals.ewedeliveryHoof.toFixed(0) }}</span>
                    </div> -->
                </div>
            </div>

            <div class="remarks-section">
                <label>备注</label>
                <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Plus,
    Document,
    RefreshLeft,
    Delete,
    Setting,
    Printer,
    Refresh
} from '@element-plus/icons-vue'
import { Writes } from '@/Utils/axiosHelper';
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
// 接口类型定义
interface DeliveryRecord {
    "ewedeliverySnowId": string,
    "ewedeliveryDayNum": number,
    "ewedeliveryDifficulty": true,
    "ewedeliveryMamhood": string,
    "ewedeliveryLactation": string,
    "ewedeliveryMastitis": string,
    "ewedeliveryHealthy": number,
    "ewedeliveryLamb": number,
    "ewedeliveryDeformities": number,
    "ewedeliveryStillbirths": number,
    "ewedeliveryNum": number,
    "ewedeliveryMummies": number,
    "ewedeliveryWoHao": string,
    "ewedeliverySex": true,
    "ewedeliveryPoultryhome": string,
    "ewedeliveryField": string,
    "ewedeliveryTransferhouse": string,
    "ewedeliveryTransfer": string,
    "remarks": string
}
interface Totals {
    ewedeliveryHealthy: number
    ewedeliveryLamb: number
    ewedeliveryDeformities: number
    ewedeliveryStillbirths: number
    ewedeliveryMummies: number
}

// 响应式数据
const formData = reactive({
    "responsibleFor": "",
    "mainDeliveryTime": "",
    "documentNumber": "",
    "serialNumber": "",
    remarks: ""
})

const tableData = ref<DeliveryRecord[]>([])
const selectedRows = ref<DeliveryRecord[]>([])
const isEditMode = ref(false)
const originalData = ref<any>(null)

// 计算属性
const hasTableData = computed(() => tableData.value.length > 0)
const hasChanges = computed(() => {
    if (!originalData.value) return false
    return JSON.stringify(formData) !== JSON.stringify(originalData.value.formData) ||
        JSON.stringify(tableData.value) !== JSON.stringify(originalData.value.tableData)
})

const isFormValid = computed(() => {
    // 检查表单必填字段
    if (!formData.responsibleFor || !formData.mainDeliveryTime) return false

    // 检查是否有表格数据
    if (tableData.value.length === 0) return false

    // // 检查是否有至少一行完整填写的数据
    // return tableData.value.some(row =>
    //     row.ewedeliverySnowId &&
    //     row.ewedeliveryDifficulty !== undefined &&
    //     row.ewedeliveryManhood &&
    //     row.ewedeliveryLactation &&
    //     row.ewedeliveryMastitis &&
    //     row.ewedeliveryHealthy !== undefined &&
    //     row.ewedeliveryDeformities !== undefined &&
    //     row.ewedeliveryStillbirths !== undefined &&
    //     row.ewedeliveryNumNums !== undefined &&
    //     row.ewedeliveryMummies !== undefined &&
    //     row.ewedeliveryHoof !== undefined &&
    //     row.ewedeliverySex !== undefined
    // )
})

// 计算合计
const totals = computed<Totals>(() => {
    return tableData.value.reduce((acc, row) => {
        acc.ewedeliveryHealthy += row.ewedeliveryHealthy || 0
        acc.ewedeliveryLamb += row.ewedeliveryLamb || 0
        acc.ewedeliveryDeformities += row.ewedeliveryDeformities || 0
        acc.ewedeliveryStillbirths += row.ewedeliveryStillbirths || 0
        acc.ewedeliveryMummies += row.ewedeliveryMummies || 0
        return acc
    }, {
        ewedeliveryHealthy: 0,
        ewedeliveryLamb: 0,
        ewedeliveryDeformities: 0,
        ewedeliveryStillbirths: 0,
        ewedeliveryMummies: 0,
    })
})
// 添加新行
const addNewRow = () => {
    const newRow: DeliveryRecord = {
        "ewedeliverySnowId": "",
        "ewedeliveryDayNum": 0,
        "ewedeliveryDifficulty": true,
        "ewedeliveryMamhood": "",
        "ewedeliveryLactation": "",
        "ewedeliveryMastitis": "",
        "ewedeliveryHealthy": 0,
        "ewedeliveryLamb": 0,
        "ewedeliveryDeformities": 0,
        "ewedeliveryStillbirths": 0,
        "ewedeliveryNum": 0,
        "ewedeliveryMummies": 0,
        "ewedeliveryWoHao": "",
        "ewedeliverySex": true,
        "ewedeliveryPoultryhome": "",
        "ewedeliveryField": "",
        "ewedeliveryTransferhouse": "",
        "ewedeliveryTransfer": "",
        "remarks": ""
    }
    tableData.value.push(newRow)
    saveOriginalData()
}
// 生成单据号和流水号
const generateDocumentNumbers = () => {
    const timestamp = Date.now()
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    // 单据号格式：PC + 年月日 + 时间戳后6位
    formData.documentNumber = `PC${year}${month}${day}${String(timestamp).slice(-6)}`

    // 流水号格式：SN + 时间戳
    formData.serialNumber = `SN${timestamp}`
}
// 顶部操作栏方法
const handleAddNew = () => {
    ElMessageBox.confirm('确定要新增记录吗？当前未保存的数据将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        resetForm()
        ElMessage.success('已重置表单')
    }).catch(() => {
        // 用户取消
    })
}


const handleUndo = () => {
    if (originalData.value) {
        Object.assign(formData, originalData.value.formData)
        tableData.value = [...(originalData.value.tableData || [])]
        ElMessage.success('已撤销更改')
    }
}

const handleDelete = () => {
    if (!isEditMode.value) {
        ElMessage.warning('请先保存记录')
        return
    }

    ElMessageBox.confirm('确定要删除当前记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteDeliveryRecord()
            resetForm()
            ElMessage.success('删除成功')
        } catch (error) {
            ElMessage.error('删除失败')
            console.error('Delete error:', error)
        }
    }).catch(() => {
        // 用户取消
    })
}

// 表格操作方法
const handleAddRow = () => {
    addNewRow()
}
// 删除选中的行
const deleteSelectedRows = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的行')
        return
    }

    const selectedIds = selectedRows.value.map(row => tableData.value.indexOf(row))
    tableData.value = tableData.value.filter((_, index) => !selectedIds.includes(index))
    selectedRows.value = []
    saveOriginalData()
    ElMessage.success(`已删除 ${selectedIds.length} 行数据`)
}

const handleDeleteRows = () => {
    if (tableData.value.length === 0) {
        ElMessage.warning('没有可删除的行')
        return
    }

    if (selectedRows.value.length > 0) {
        // 删除选中的行
        deleteSelectedRows()
    } else {
        // 如果没有选择行，默认删除最后一行
        tableData.value.pop()
        saveOriginalData()
        ElMessage.success('已删除最后一行')
    }
}

const handleCleanInvalidRows = () => {
    const originalLength = tableData.value.length
    // tableData.value = tableData.value.filter(row =>
    //     row.ewedeliverySnowId &&
    //     row.ewedeliveryDifficulty !== undefined &&
    //     row.ewedeliveryManhood &&
    //     row.ewedeliveryLactation &&
    //     row.ewedeliveryMastitis &&
    //     row.ewedeliveryHealthy !== undefined &&
    //     row.ewedeliveryDeformities !== undefined &&
    //     row.ewedeliveryStillbirths !== undefined &&
    //     row.ewedeliveryNumNums !== undefined &&
    //     row.ewedeliveryMummies !== undefined &&
    //     row.ewedeliveryHoof !== undefined &&
    //     row.ewedeliverySex !== undefined
    // )

    const removedCount = originalLength - tableData.value.length
    if (removedCount > 0) {
        ElMessage.success(`已清理 ${removedCount} 行不完整的记录`)
        saveOriginalData()
    } else {
        ElMessage.info('没有找到不完整的记录')
    }
}
const handleSelectionChange = (selection: DeliveryRecord[]) => {
    selectedRows.value = selection || []
}

// 表单验证
const validateForm = (): boolean => {
    // 验证表格数据
    for (let i = 0; i < tableData.value.length; i++) {
        const row = tableData.value[i]
        if (!row) continue

        if (!row.ewedeliverySnowId) {
            ElMessage.error(`第 ${i + 1} 行耳号不能为空`)
            return false
        }
        if (row.ewedeliveryDifficulty === undefined || row.ewedeliveryDifficulty === null) {
            ElMessage.error(`第 ${i + 1} 行分娩难易不能为空`)
            return false
        }
    }

    return true
}

const validateRequiredField = (row: DeliveryRecord, field: keyof DeliveryRecord, index: number) => {
    if (!row[field]) {
        ElMessage.warning(`第 ${index + 1} 行${getFieldLabel(field)}不能为空`)
        return false
    }
    return true
}

const getFieldLabel = (field: keyof DeliveryRecord): string => {
    const labels: { [key: string]: string } = {
        ewedeliverySnowId: '耳号',
        ewedeliveryDifficulty: '分娩难易'
    }
    return labels[field] || field
}

// 重置表单
const resetForm = () => {
    Object.assign(formData, {
        responsibleFor: '',
        mainDeliveryTime: '',
        documentNumber: '',
        serialNumber: '',
        remarks: ''
    })
    generateDocumentNumbers()
    tableData.value = []
    selectedRows.value = []
    isEditMode.value = false
    originalData.value = null
    // 初始化一行数据
    addNewRow()
}
onMounted(() => {
    generateDocumentNumbers()
})
// 保存原始数据（用于撤销功能）
const saveOriginalData = () => {
    originalData.value = {
        formData: { ...formData },
        tableData: [...(tableData.value || [])]
    }
}

// ========== 后端接口方法 ==========

// 保存处理
const handleSave = async () => {
    if (!validateForm()) {
        return
    }

    try {
        ElMessage.info('正在保存...')
        await createDeliveryRecord()
        ElMessage.success('保存成功')
        isEditMode.value = true
        saveOriginalData()
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请检查输入信息')
    }
}

// 创建分娩记录
const createDeliveryRecord = async () => {
    // 校验表单必填字段
    if (!formData.responsibleFor) {
        ElMessage.warning('请选择负责人')
        return
    }

    if (!formData.mainDeliveryTime) {
        ElMessage.warning('请选择分娩日期')
        return
    }

    // 校验表格数据
    if (!tableData.value || tableData.value.length === 0) {
        ElMessage.warning('请至少添加一条分娩记录')
        return
    }

    // 过滤并校验有效数据
    const validRows = tableData.value.filter(row =>
        row.ewedeliverySnowId &&
        row.ewedeliveryDifficulty !== undefined
    )

    if (validRows.length === 0) {
        ElMessage.warning('请至少填写一条完整的数据（耳号、分娩难易）')
        return
    }

    // 转换日期格式：从 YYYY/MM/DD 转换为 ISO 格式
    let formattedDate = formData.mainDeliveryTime
    if (formattedDate && formattedDate.includes('/')) {
        // 将 YYYY/MM/DD 转换为 YYYY-MM-DD
        formattedDate = formattedDate.replace(/\//g, '-')
        // 如果没有时间部分，添加默认时间
        if (!formattedDate.includes('T')) {
            formattedDate = `${formattedDate}T00:00:00`
        }
    }

    const payload = {
        responsibleFor: formData.responsibleFor,
        mainDeliveryTime: formattedDate,
        documentNumber: formData.documentNumber || '',
        serialNumber: formData.serialNumber || '',
        ewedeliverysList: validRows.map(row => ({
            ewedeliverySnowId: row.ewedeliverySnowId,
            ewedeliveryDayNum: row.ewedeliveryDayNum || 0,
            ewedeliveryDifficulty: row.ewedeliveryDifficulty,
            ewedeliveryMamhood: row.ewedeliveryMamhood || '', // Swagger中使用ewedeliveryMamhood而不是ewedeliveryManhood
            ewedeliveryLactation: row.ewedeliveryLactation || '',
            ewedeliveryMastitis: row.ewedeliveryMastitis || '',
            ewedeliveryHealthy: row.ewedeliveryHealthy || 0,
            ewedeliveryLamb: row.ewedeliveryDeformities || 0, // 弱羔数 - 代码中字段名是ewedeliveryDeformities
            ewedeliveryDeformities: row.ewedeliveryStillbirths || 0, // 畸形数 - 代码中字段名是ewedeliveryStillbirths
            ewedeliveryStillbirths: row.ewedeliveryStillbirths || 0, // 死胎数 - 代码中字段名是ewedeliveryNumNums
            // ewedeliveryNum: row.ewedeliveryHoof || 0, // 活羔数 - 代码中字段名是ewedeliveryHoof
            ewedeliveryMummies: row.ewedeliveryMummies || 0,
            ewedeliveryWoHao: row.ewedeliveryWoHao || 0, // Swagger中额外的字段（与ewedeliveryNum同值）
            ewedeliverySex: row.ewedeliverySex !== undefined ? row.ewedeliverySex : true,
            ewedeliveryPoultryhome: row.ewedeliveryPoultryhome || '',
            ewedeliveryField: row.ewedeliveryField || '',
            ewedeliveryTransferhouse: row.ewedeliveryTransferhouse || '',
            ewedeliveryTransfer: row.ewedeliveryTransfer || '',
            remarks: row.remarks || ''
        }))
    }

    console.log('批量添加请求数据:', payload)
    const response = await Writes.post('Management/AddBatchEwedeliverys', payload)
    console.log('批量添加响应:', response)

    if (response.data.code == 100) {
        ElMessage.success(`批量添加成功，共添加${validRows.length}条记录`)
        router.push('/EweEwedeliveryList');
        // 添加成功后，更新表格中的数据为编辑模式
        // 保存成功后，更新原始数据以支持撤销功能
        saveOriginalData()
    } else {
        ElMessage.error(response.data.msg || '批量添加失败')
    }
}

// 更新分娩记录
const updateDeliveryRecord = async () => {
    const payload = {
        id: formData.documentNumber,
        formData: { ...formData },
        records: tableData.value.map((row, index) => ({
            ...row,
            serialNo: index + 1
        })),
        totals: { ...totals.value }
    }

    // TODO: 调用后端更新接口
    // const response = await api.put(`/api/delivery-records/${payload.id}`, payload)
    console.log('更新分娩记录:', payload)

    // 模拟接口调用
    return new Promise((resolve) => {
        setTimeout(() => resolve(true), 1000)
    })
}

// 删除分娩记录
const deleteDeliveryRecord = async () => {
    const id = formData.documentNumber

    // TODO: 调用后端删除接口
    // const response = await api.delete(`/api/delivery-records/${id}`)
    console.log('删除分娩记录:', id)

    // 模拟接口调用
    return new Promise((resolve) => {
        setTimeout(() => resolve(true), 1000)
    })
}

// 获取分娩记录详情（用于编辑模式）
const getDeliveryRecordDetail = async (id: string) => {
    // TODO: 调用后端获取详情接口
    // const response = await api.get(`/api/delivery-records/${id}`)
    console.log('获取分娩记录详情:', id)

    // 模拟接口调用
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                formData: {
                    responsibleFor: 'zhangsan',
                    mainDeliveryTime: '2023/03/31',
                    documentNumber: 'DR20230331001',
                    serialNumber: 'SN20230331001',
                    remarks: '测试备注'
                },
                records: [
                    {
                        ewedeliverySnowId: 'E001',
                        ewedeliveryDayNum: 150,
                        ewedeliveryDifficulty: true,
                        ewedeliveryMamhood: '良好',
                        ewedeliveryLactation: '良好',
                        ewedeliveryMastitis: '无',
                        ewedeliveryHealthy: 2,
                        ewedeliveryDeformities: 0,
                        ewedeliveryStillbirths: 0,
                        ewedeliveryNumNums: 0,
                        ewedeliveryMummies: 0,
                        ewedeliveryHoof: 2,
                        ewedeliverySex: true,
                        ewedeliveryPoultryhome: 'A栋',
                        ewedeliveryField: 'A01',
                        ewedeliveryTransferhouse: 'B栋',
                        ewedeliveryTransfer: 'B01'
                    }
                ]
            })
        }, 1000)
    })
}

// 组件挂载时初始化
onMounted(() => {
    // 初始化一行数据
    addNewRow()
})
</script>

<style scoped>
.ewe-delivery-view {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 顶部操作栏 */
.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 15px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.action-left {
    display: flex;
    gap: 10px;
}

.action-right {
    display: flex;
    gap: 15px;
}

.action-icon {
    font-size: 18px;
    color: #666;
    cursor: pointer;
    transition: color 0.3s;
}

.action-icon:hover {
    color: #409eff;
}

/* 表单区域 */
.form-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.form-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-item label {
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

.form-item label.required::after {
    content: ' *';
    color: #f56c6c;
}

/* 表格区域 */
.table-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

/* 底部区域 */
.footer-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.summary-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.summary-label {
    font-weight: 600;
    font-size: 16px;
    color: #333;
}

.row-actions {
    display: flex;
    gap: 10px;
    align-items: center;
}

.row-actions :deep(.el-button) {
    border-radius: 4px;
    font-weight: 500;
    padding: 8px 16px;
}

.totals-section {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
    padding: 12px 15px;
    background-color: #f8f9fa;
    border-radius: 4px;
    flex-wrap: wrap;
}

.total-item {
    display: flex;
    align-items: center;
    gap: 5px;
    min-width: 80px;
}

.total-label {
    font-weight: 500;
    color: #666;
    font-size: 13px;
    white-space: nowrap;
}

.total-value {
    font-weight: 600;
    color: #333;
    font-size: 14px;
    min-width: 50px;
    text-align: right;
}

.remarks-section {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.remarks-section label {
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 6px;
    overflow: hidden;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #333;
    font-weight: 600;
    border-bottom: 1px solid #ebeef5;
    padding: 8px 0;
}

:deep(.el-table td) {
    padding: 6px 0;
    border-bottom: 1px solid #ebeef5;
}

:deep(.el-input) {
    width: 100%;
}

:deep(.el-select) {
    width: 100%;
}

:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-input-number .el-input__inner) {
    text-align: center;
}

/* 表格行样式 */
:deep(.el-table .el-table__row) {
    height: 40px;
}

:deep(.el-table .el-table__row:hover) {
    background-color: #f8f9fa;
}

/* 表格单元格样式 */
:deep(.el-table .el-table__cell) {
    padding: 0 4px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
    .totals-section {
        flex-wrap: wrap;
        gap: 20px;
    }
}

@media (max-width: 1200px) {
    .form-row {
        grid-template-columns: repeat(2, 1fr);
    }

    .totals-section {
        justify-content: space-between;
    }
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }

    .action-left {
        flex-wrap: wrap;
    }

    .ewe-delivery-view {
        padding: 10px;
    }

    .totals-section {
        flex-direction: column;
        gap: 10px;
    }

    .summary-section {
        flex-direction: column;
        gap: 15px;
        align-items: flex-start;
    }
}
</style>

